package com.ca.ridersclubapplication.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.ca.ridersclubapplication.AccountActivity;
import com.ca.ridersclubapplication.AccountListActivity;
import com.ca.ridersclubapplication.ClubListActivity;
import com.ca.ridersclubapplication.HistoryListActivity;
import com.ca.ridersclubapplication.ImageActivity;
import com.ca.ridersclubapplication.MainActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.UpdateActivity;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.bean.ClubInfo;
import com.ca.ridersclubapplication.data.bean.MiniComment;
import com.ca.ridersclubapplication.data.bean.PaperInfo;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.data.entity.Token;
import com.ca.ridersclubapplication.request.AccountRequester;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.ClubRequester;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.AccountDto;
import com.ca.ridersclubapplication.request.dto.AccountUpdateDto;
import com.ca.ridersclubapplication.request.dto.ClubDto;
import com.ca.ridersclubapplication.request.dto.CommentDto;
import com.ca.ridersclubapplication.request.dto.HistoryDto;
import com.ca.ridersclubapplication.request.dto.PaperInfoDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.util.PaperUtils;
import com.ca.ridersclubapplication.util.TransitionUtils;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.bar.MiniMainTitleBar;
import com.ca.ridersclubapplication.view.button.CountValueButton;
import com.ca.ridersclubapplication.view.card.AccountCard;
import com.ca.ridersclubapplication.view.card.PaperHistoryCard;
import com.ca.ridersclubapplication.view.list.FollowClubListView;

import java.util.ArrayList;
import java.util.List;

public class MyFragment extends Fragment implements RefreshableFragment {

    private ConstraintLayout parentCL;

    private ConstraintLayout mainTitleCL;
    private MiniMainTitleBar miniTitleBar;

    private NestedScrollView nsv;

    private AccountCard accountCard;

    private CountValueButton paperCountButton;
    private CountValueButton followCountButton;
    private CountValueButton fansCountButton;

    private FollowClubListView followClubListView;

    private PaperHistoryCard paperHistoryCard;

    private Button logoutButton;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_my_layout, container, false);

        //  初始化视图
        initView(view);

        //  设置监听器
        initListener();

        loadData();

        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initView(View view) {

        parentCL = view.findViewById(R.id.cl_parent);

        //  标题栏
        mainTitleCL = view.findViewById(R.id.cl_mainTitle);
        miniTitleBar = view.findViewById(R.id.bar_miniTitle);

        //  滑动容器
        nsv = view.findViewById(R.id.nsv);

        //  顶部的账号卡片
        accountCard = view.findViewById(R.id.card_account);

        paperCountButton = view.findViewById(R.id.btn_paperCount);
        followCountButton = view.findViewById(R.id.btn_followCount);
        fansCountButton = view.findViewById(R.id.btn_fansCount);

        //  关注车友会列表卡片
        followClubListView = view.findViewById(R.id.lv_followClub);
        followClubListView.setActivity(getActivity());

        //  设置标题栏头像、名字Alpha
        miniTitleBar.headerView.setAlpha(0f);
        miniTitleBar.nameView.setAlpha(0f);
        mainTitleCL.setElevation(0f);

        //  浏览历史卡片
        paperHistoryCard = view.findViewById(R.id.card_paperHistory);
        paperHistoryCard.setActivity(getActivity());

        //  退出登录按钮
        logoutButton = view.findViewById(R.id.btn_logout);
        logoutButton.setBackgroundColor(getResources().getColor(R.color.danger));

        //  历史记录会因用户查看的文章而发生变化，因此放入数据处理器中
        DataHandler.putView("AddHistory", new CallbackView() {
            @Override
            public void update() {
                //  请求历史记录
                listHistory();
            }
        });

        Long accountId = DataHandler.getToken(getActivity()).getId();
        DataHandler.putView("AccountUpdateDto:" + accountId, new CallbackView() {
            @Override
            public void update() {
                //  重新加载数据
                refresh();
            }
        });
    }

    private void initListener() {

        //  监听NSV滑动事件，调整标题栏样式（隐藏、显示头像、海拔等）
        nsv.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> accountCard.post(() -> {

            if (scrollY == 0) {
                miniTitleBar.headerView.setAlpha(0f);
                miniTitleBar.nameView.setAlpha(0f);
                mainTitleCL.setElevation(0f);
                return;
            }

            float ratio = 1.0f * scrollY / (accountCard.getHeight() + 64);
            float alpha = ratio > 1 ? 1 : ratio;
            miniTitleBar.headerView.setAlpha(alpha);
            miniTitleBar.nameView.setAlpha(alpha);
            mainTitleCL.setElevation(ratio > 1 ? 4 : ratio * 4);
        }));

        //  退出按钮点击
        logoutButton.setOnClickListener(v -> {
            DataHandler.logout(getActivity());
            //  转到首页
            MainActivity.gotoPage(0);
        });

        //  数据按钮点击事件
        Long id = DataHandler.getToken(getActivity()).getId();
        paperCountButton.setOnClickListener(v -> {
            Token token = DataHandler.getToken(getActivity());
            Intent intent = new Intent(getActivity(), AccountActivity.class);
            intent.putExtra("accountId", token.getId());
            startActivity(intent);
        });

        followCountButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AccountListActivity.class);
            intent.putExtra("accountId", id);
            intent.putExtra("type", "followList");
            startActivity(intent);
        });

        fansCountButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AccountListActivity.class);
            intent.putExtra("accountId", id);
            intent.putExtra("type", "fansList");
            startActivity(intent);
        });

        followClubListView.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ClubListActivity.class);
            intent.putExtra("classify", "follow:" + id);
            startActivity(intent);
        });

        paperHistoryCard.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), HistoryListActivity.class);
            startActivity(intent);
        });
    }

    public void showMiniTitle() {
        if (mainTitleCL != null && mainTitleCL.getVisibility() == View.GONE) {
            TransitionUtils.fadeInView(mainTitleCL);
        }
    }

    public void hideMiniTitle() {
        TransitionUtils.fadeOutView(mainTitleCL);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void clearData() {
        if (paperHistoryCard != null) {
            paperHistoryCard.setList(new ArrayList<>());
        }
        if (followClubListView != null) {
            followClubListView.setInfoList(new ArrayList<>());
        }
        if (accountCard != null) {
            accountCard.setGrade("0");
            accountCard.setName("");
            accountCard.setHeaderUrl("");
        }
    }

    @Override
    public void refresh() {
        loadData();
    }

    private void loadData() {

        //  请求账号数据
        getAccount();

        //  请求关注车友会列表
        listFollowClub();

        //  请求历史记录
        listHistory();
    }

    private void getAccount() {
        AccountRequester.getAccount(getActivity(), DataHandler.getToken(getActivity()).getId(), new AfterExecutor<AccountDto>() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void execute(Result<AccountDto> result) {
                AccountDto dto = result.getData();
                if (result.isSuccess() && dto != null) {
                    //  请求成功，设置数据
                    miniTitleBar.setHeaderUrl(FileRequester.HEADER_BY_ID_BASE_URL + dto.getId());
                    miniTitleBar.setName(dto.getNickname());
                    ImageView headerView = accountCard.headerView;
                    ImageUtils.loadCircleImage(getContext(), FileRequester.HEADER_BY_ID_BASE_URL + dto.getId(), headerView);
                    accountCard.nameView.setText(dto.getNickname());
                    accountCard.setGrade(String.valueOf(dto.getGrade()));
                    accountCard.setGradeCurrentValue(dto.getCurrentGradeValue());
                    accountCard.setGradeMaxValue(dto.getMaxGradeValue());
                    paperCountButton.setValue(dto.getPaperCount());
                    followCountButton.setValue(dto.getFollowCount());
                    fansCountButton.setValue(dto.getFansCount());

                    if (dto.getProfile() != null && dto.getProfile().trim().isEmpty()) {
                        accountCard.profileView.setVisibility(View.GONE);
                    }
                    else {
                        accountCard.profileView.setVisibility(View.VISIBLE);
                        accountCard.profileView.setText(dto.getProfile());
                    }
                    String gender = dto.getGender();
                    if (gender.equals("男")) {
                        accountCard.genderTV.setText("男");
                        accountCard.genderIV.setImageDrawable(getResources().getDrawable(R.drawable.ic_man));
                        accountCard.genderCL.setBackground(getResources().getDrawable(R.drawable.gender_man_bg));
                        accountCard.genderCL.setVisibility(View.VISIBLE);
                    }
                    else if (gender.equals("女")) {
                        accountCard.genderTV.setText("女");
                        accountCard.genderIV.setImageDrawable(getResources().getDrawable(R.drawable.ic_femal));
                        accountCard.genderCL.setBackground(getResources().getDrawable(R.drawable.gender_femal_bg));
                        accountCard.genderCL.setVisibility(View.VISIBLE);
                    }
                    else {
                        accountCard.genderCL.setVisibility(View.GONE);
                    }

                    //  点击头像
                    View.OnClickListener hil = v -> {
                        FragmentActivity activity = getActivity();
                        if (activity != null) {
                            //  修改信息界面
                            Intent intent = new Intent(getActivity(), UpdateActivity.class);
                            activity.startActivity(intent);
                        }
                    };
                    miniTitleBar.setOnClickListener(hil);
                    headerView.setOnClickListener(hil);
                }
            }
        });
    }

    private void listFollowClub() {
        ClubRequester.listFollowClub(getActivity(), DataHandler.getToken(getActivity()).getId(), new AfterExecutor<List<ClubDto>>() {
            @Override
            public void execute(Result<List<ClubDto>> result) {
                List<ClubDto> data = result.getData();
                if (result.isSuccess() && data != null) {
                    //  请求成功，设置数据
                    List<ClubInfo> list = new ArrayList<>();
                    for (ClubDto dto : data) {
                        list.add(new ClubInfo(
                                dto.getId(),
                                FileRequester.CLUB_IMAGE_1_1_BASE_URL + dto.getId(),
                                dto.getName(),
                                dto.getPaperCount()
                        ));
                    }
                    followClubListView.setInfoList(list);
                }
            }
        });
    }

    private void listHistory() {
        PaperRequester.listHistory(getActivity(), Long.MAX_VALUE, new AfterExecutor<List<HistoryDto>>() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void execute(Result<List<HistoryDto>> result) {
                List<HistoryDto> data = result.getData();
                if (result.isSuccess() && data != null) {
                    //  请求成功，设置数据
                    paperHistoryCard.setList(data);

                    //  关闭刷新动画
                    MainActivity activity = (MainActivity) getActivity();
                    if (activity != null) {
                        activity.stopRefreshing();
                    }
                }
            }
        });
    }
}
